package org.example.mapper;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.w3c.dom.NodeList;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import java.util.*;

public class XpathTest {
    public static List<String> insertxml(String a, String b) {
        List<String> list = null;
        try {
            // 从XML字符串创建一个InputSource对象
            InputSource source = new InputSource(a);
            // 创建一个DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 创建一个DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 使用DocumentBuilder解析输入源，创建一个Document对象
            Document document = builder.parse(source);
            // 创建XPath对象
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            // 编写XPath表达式
            String expression = b;
            // 使用XPath对象执行XPath查询
            NodeList nodeList = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
            list = new ArrayList<>();

            // 遍历查询结果
            for (int i = 0; i < nodeList.getLength(); i++) {

                list.add(nodeList.item(i).getTextContent().toString());
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}